<template>
  <div class="">
    <h2>图书管理</h2>
    标题：<input type="text" v-model="title" /> 价格：<input
      type="text"
      v-model="price"
    />
    <button @click="add">操作</button>
    <hr />
    <table>
      <thead>
        <tr>
          <!-- <th>id</th> -->
          <th>title</th>
          <th>价格</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="(item, index) in list" :key="item.id">
          <!-- <td>{{ item.id }}</td> -->
          <td>{{ item.title }}</td>
          <td>{{ item.price }}</td>
          <td>
            <button @click="edit(item, index)">修改</button
            ><button @click="remove(index)">删除</button>
          </td>
        </tr>
      </tbody>
    </table>
  </div>
</template>

<script>
export default {
  data() {
    return {
      list: [
        {
          id: 1,
          title: "vue从入门到放弃",
          price: 100,
        },
        {
          id: 2,
          title: "vue从入门到放弃2",
          price: 200,
        },
        {
          id: 3,
          title: "vue从入门到放弃3",
          price: 300,
        },
      ],
      title: "",
      price: "",
      isedit: false,
      //是否修改
      editindex: -1,
      //保存当前修改的下标
    };
  },
  mounted() {},
  methods: {
    add() {
      if (this.isedit == false) {
        this.list.push({
          id: new Date().getTime(),
          title: this.title,
          price: this.price,
        });
      } else {
        this.list[this.editindex].title = this.title;
        this.list[this.editindex].price = this.price;
        this.isedit = false;
        // this.editindex = -1;
      }
    },
    //点击操作按钮 如果isedit是false证明没有编辑，就可以添加，如果是true证明在编辑 那么就执行修改
    remove(i) {
      this.list.splice(i, 1);
    },
    //删除
    edit(item, index) {
      this.isedit = true;
      this.title = item.title;
      this.price = item.price;
      this.editindex = index;
    },
    //按下修改按钮 数据回填 并且保存修改的数据的下标
  },
  components: {},
};
</script>

<style lang="scss"></style>
